package firstappdemo.repository;

import firstappdemo.domain.User;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author liujs@centaline.com.cn
 * @date 2020/2/12 13:49
 * {@link User} {@lint Repository}
 */
@Repository
public class UserRepository {
    /**
     * 采用内存方式保存->Map
     */
    private final ConcurrentMap<Integer, User> repository = new ConcurrentHashMap<>();

    private final AtomicInteger idGenerator = new AtomicInteger();

    /**
     * 保存用户对象
     *
     * @param user {@link User}
     * @return 如果保存成功，返回<code>true</code>
     * 否则,返回<code>false</code>
     */
    public boolean save(User user) {
        //id 从1开始
        Integer id=idGenerator.incrementAndGet();
        user.setId(id);
        return repository.put(id,user)==null;
    }
    /**
     * 返回所有用户列表
     */
    public Collection<User> findAll(){
        return repository.values();
    }
}
